package de.uni_saarland.coli.doclists.suffixtree.memory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import de.uni_saarland.coli.doclists.data.btree.MemoryMapData;
import de.uni_saarland.coli.doclists.suffixtree.INodeManager;
import de.uni_saarland.coli.doclists.suffixtree.STreeNode;

/**
 * 
 * @author stefan
 * 
 *         manages suffix tree nodes in memory
 */
public class MemoryNodeManager implements INodeManager {

	/**
	 * the next node id
	 */
	private int nextNodeID = 0;
	
	/**
	 * the nodes
	 */
	private MemoryMapData<STreeNode> nodeMap;

	/**
	 * Constructor.
	 */
	public MemoryNodeManager() {
		this.nodeMap = new MemoryMapData<STreeNode>();
		// create root
		// this.createNode();
	}

	@Override
	public STreeNode createNode() {
		STreeNode newNode = new STreeNode(nextNodeID);
		nodeMap.add(nextNodeID, newNode);

		nextNodeID++;

		return newNode;
	}

	@Override
	public STreeNode getNode(int id) {
		return nodeMap.get(id);
	}

	@Override
	public int getNextNodeID() {
		return nextNodeID;
	}

	@Override
	public void save(String path, String baseName) {
		this.nodeMap.save(path, baseName + ".nodes");
		
		FileOutputStream fos = null;
		ObjectOutputStream out = null;

		try {
			fos = new FileOutputStream(path + "/" + baseName + ".nodeCount");
			out = new ObjectOutputStream(fos);
			out.writeObject(this.nextNodeID);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		
	}

	@Override
	public void open(String path, String baseName) {
		this.nodeMap.open(path, baseName + ".nodes");
		
		FileInputStream fis = null;
		ObjectInputStream in = null;

		try {
			fis = new FileInputStream(path + "/" + baseName + ".nodeCount");
			in = new ObjectInputStream(fis);
			this.nextNodeID = (Integer) in.readObject();
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
